﻿using System;
using System.Collections.Generic;
using System.Text;
using Xeno.Core;
using Xeno.Maths;
using Xeno.Module;
using Xeno.GUI;

using OpenTK;
using OpenTK.Audio;
using OpenTK.Graphics;
using OpenTK.Input;
using OpenTK.Platform;
using PhysX.NET;

namespace Xeno.Physics
{
    public class XenoPhysicsManager : XenoModule
    {
        public float TimeStep { get; set; }
        public PhysX.NET.NxPhysicsSDK SDK { get; set; }
        public NxScene Scene { get; set; }
        public float TimeMod { get; set; }
        NxPhysicsSDK desc = null;
        NxSceneDesc sdesc = null;
        public NxVec3 Gravity { get; set; }
        public XenoPhysicsManager(string name) 
        {
            PhysX.NET.NxPhysicsSDKDesc desc = new NxPhysicsSDKDesc();
            NxSDKCreateError err = new NxSDKCreateError();
            SDK = PhysXLoader.NxCreatePhysicsSDK(PhysXLoader.NX_PHYSICS_SDK_VERSION, desc, ref err);
            if (SDK == null)
            {
                XenoDebug.LogError("Could not initiate Physics manager. Underlying technology not supported or drivers not installed.", "XenoPhysicsManager.ctor()");

            }
            TimeStep = 0.1f;
            TimeMod = 1.0f;
            SDK.setParameter(NxParameter.NX_SKIN_WIDTH, 0.05f);
            NxSceneDesc sdesc = new NxSceneDesc();
            NxVec3 vec = new NxVec3();
            vec.x = 0;
            vec.y = -9.81f;
            vec.z = 0;
            sdesc.gravity = vec;
            Gravity = vec;
            Scene = SDK.createScene(sdesc);
            if (Scene == null)
            {

                XenoDebug.LogError("Could not initiate Physics manager. Underlying technology could not created a phsyical scene.", "XenoPhysicsManager.ctor()");

            }
           
            NxMaterial mat = Scene.getMaterialFromIndex(0);
            mat.setRestitution(0.0f);
            mat.setStaticFriction(0.5f);
            mat.setDynamicFriction(0.5f);
            Scene.setGravity(ref vec);
            
        }

     
          
        public override void DoUpdate()
        {
            
            Scene.simulate(1);
            Scene.flushStream();
            Scene.flushCaches();
            Scene.fetchResults(NxSimulationStatus.NX_ALL_FINISHED);
            
        }

    }
}
